<template>
  <div class="page-controller">
    <FISearchForm
      class="box-radius2"
      ref="ruleFormRef"
      :id="`inqu_${tableId}`"
      :searchNum="searchItemCount"
      :showCollapse="false"
      v-model:form-value="state.query"
      :table-column="columns"
      :wrapperSpan="searchWrapperSpan"
      @submit="searchFn"
    >
      <el-col :span="searchWrapperSpan" class="flex-center">
        <FIFormItem prop="loginName" label="用户">
          <FIAutoSelect
            v-model="state.query.loginName"
            :props="{ value: 'loginName', label: 'userName' }"
            :display-key="['loginName','userName']"
            api-url="/rm2/userMaint/query"
            searchParam="userAName"
          />
        </FIFormItem>
      </el-col>
    </FISearchForm>
    <div class="margin-bottom20"></div>
    <FITable
      ref="tableRef"
      class="box-radius2"
      title="用户权限审计列表"
      :id="`result_${tableId}`"
      :readonly="false"
      :checkMode="'index'"
      :data="state.dataList"
      primaryKey="formId"
      v-model:columns="columns"
      :insertable="false"
      :isLoading="isTableLoading"
      :saveSuccessful="saveSuccessful"
      :pageConfig="pageConfig"
      @row-add-save="addRowSave"
      @table-refresh="searchFn"
      @selection-change="handleSelectionChange"
      @size-change="handleSizeChange"
      @current-page-change="handleCurrentChange"
    >
      <template #headerBtn>
        <FIButton id="export" border class="margin-left5" @click.stop="exportRow"></FIButton>
      </template>
    </FITable>
  </div>
</template>
<script lang="ts" setup>
import { reactive, onMounted, ref, computed, watch } from 'vue'
import FISearchForm from '@/components/FISearchForm.vue'
import FIFormItem from '@/components/FIFormItem.vue'
import FIInput from '@/components/FIInput.vue'
import FIButton from '@/components/FIButton.vue'
import FIPopconfirmBtn from '@/components/FIPopconfirmBtn.vue'
import FITable from '@/components/FITable/index.vue'
import FISelect from '@/components/FISelect/index.vue'

import { apiRequestPost, apiRequestExport } from '@/api/globalApi.js'
import LocalCache from '@/utils/cache'
import { ElMessage } from 'element-plus'
import { useMessage } from '@/hooks/message'
import type { PageConfig, Column } from '@/types/components'
import { useRoute } from 'vue-router'
import { initSearchData } from '@/utils/common'
import { getQueryTableCache } from '@/utils/cacheUtils'
import { apiPageFullAuth, apiExportFullAuth, apiUserquery } from '@/api/user'
import { getCurrentInstance } from 'vue'
const { proxy } = getCurrentInstance() // 获取当前组件实例上下文
const route = useRoute()
const searchWrapperSpan = 8
const showSearch = ref(true)
const isTableLoading = ref(false)
const usersList = ref([])
// 页面编码
const tableId = 'userauthAudit'
// 保存成功按钮状态，默认不展示底部保存，取消按钮
const saveSuccessful = ref(false)
const tableRef = ref(null)
const userlistCurrent = ref(1)
const loadMoreEnd = ref(false)
const state = reactive({
  query: {
    loginName: '',
    current: 1,
    size: 10,
  },
  dataList: [],
})
const pageConfig: PageConfig = reactive({
  total: 0,
  currentPage: 1,
})
const columns: Column[] = reactive([
  {
    label: '用户',
    prop: 'userName',
    align: 'center',
    editable: false,
    editType: 'input',
  },
  {
    label: '部门',
    prop: 'orgCname',
    align: 'center',
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
  {
    label: '岗位',
    prop: 'postCname',
    align: 'center',
    editable: false,
  },
  {
    label: '用户组',
    prop: 'groupCname',
    align: 'center',
    editable: false,
  },
  {
    label: '菜单',
    prop: 'menuPath',
    align: 'center',
    editable: false,
  },
  {
    label: '页面',
    prop: 'objectCName',
    align: 'center',
    editable: false,
  },
  {
    label: '按钮',
    prop: 'buttonCname',
    align: 'center',
    editable: false,
  },
])

const checkedRows = ref([])
const handleSelectionChange = (e) => {
  checkedRows.value = e
}
const handleSizeChange = (e) => {
  pageConfig.pageSize = e
  pageConfig.currentPage = 1
  searchFn()
}
const handleCurrentChange = (e) => {
  pageConfig.currentPage = e
  searchFn('page')
}
//导出
const exportRow = () => {
  // const apiUrl = proxy.$Button_api('export', route.name)
  apiExportFullAuth(state.query)
}
// 隐藏搜索项有值的个数
const searchItemCount = computed(() => {
  let filledCount = 0
  const outKeys = ['dynamicParams', 'orderbyParams', 'size', 'current']
  // 下面是从第三项起计算常规搜索条件有值个树
  // 获取state.query的所有keys
  const queryKeys = Object.keys(state.query).filter((key) => !outKeys.includes(key))
  if (queryKeys.length < 3) return 0
  // 从第三项开始计算
  queryKeys.slice(2).forEach((key) => {
    if (state.query[key] !== '' && state.query[key] !== null) {
      filledCount++
    }
  })
  return filledCount
})
const searchFn = (type?: string, columnsVal?: any) => {
  // if (!state.query.loginName) {
  //   useMessage().warning('请选择用户账号')
  //   return
  // }
  const obj = initSearchData(type, columnsVal, columns, state.query)
  state.query = obj.queryData
  columns.values = obj.columns

  if(type == 'page'){
    state.query.current = pageConfig.currentPage
  }else{
    pageConfig.currentPage = 1
    state.query.current = 1
  }
  isTableLoading.value = true
  if (pageConfig.pageSize) state.query.size = pageConfig.pageSize
  apiPageFullAuth(state.query)
    .then((res) => {
      isTableLoading.value = false
      if (res.data.success) {
        state.dataList = res.data.data.result
        pageConfig.pageSize = Number(res.data.data.size)
        pageConfig.total = Number(res.data.data.count)
      } else {
        // ElMessage.error(res.data.message)
      }
    })
    .catch((error: any) => {
      isTableLoading.value = false
      // 处理错误
    })
}
// const handleSave = () => {
//   isTableLoading.value = true
//   saveSuccessful.value = false
//   apiRequestPost('/rm2/pageMaint/save', checkedRows.value)
//     .then((res) => {
//       isTableLoading.value = false
//       if (res.data.success) {
//         // saveSuccessful.value = true
//         tableRef.value.clearSelection()
//         searchFn()
//       } else {
//         ElMessage.error(res.data.message)
//       }
//     })
//     .catch((error: any) => {
//       isTableLoading.value = false
//     })
// }
// //导出
// const exportRow = () => {
//   if (!checkedRows.value.length) {
//     useMessage().warning('请选择一条数据')
//     return
//   }
//   let ids = []
//   Array.isArray(checkedRows.value) &&
//     checkedRows.value.forEach((item: any) => {
//       if (item?.formId) ids.push(item?.formId)
//     })
//   isTableLoading.value = true
//   apiUserAuthExport(ids)
//     .then((res) => {
//       isTableLoading.value = false
//       searchFn()
//     })
//     .catch((error: any) => {
//       isTableLoading.value = false
//     })
// }
const ruleFormRef = ref(null)

const addRowSave = (data) => {
  // handleSave()
}
const loadMore = () => {
  console.log('------------------000002')
  if (loadMoreEnd.value && userlistCurrent.value > 1) return
  userlistCurrent.value++
  getUserList()
}
const getUserList = () => {
  let par = {
    current: userlistCurrent.value,
    size: 10,
  }
  apiUserquery(par)
    .then((res) => {
      isTableLoading.value = false
      if (res.data.success) {
        usersList.value = usersList.value.concat(res.data.data.result)
        if (userlistCurrent.value * 10 >= res.data.data.count) {
          loadMoreEnd.value = true
        }
      }
    })
    .catch((error: any) => {
      isTableLoading.value = false
      // 处理错误
    })
}
onMounted(() => {
  // 获取查询条件缓存
  const { cachedQuery, cachedColumns } = getQueryTableCache(route.path, tableId, state.query, columns.values)
  if (cachedQuery) state.query = cachedQuery
  if (columns) columns.values = cachedColumns
  searchFn()
  getUserList()
})
</script>
<style lang="less" scoped></style>
